package com.itheima.filter;

import com.itheima.common.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Configuration
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 拦截鉴权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //客户端数据的封装
        ServerHttpRequest request = exchange.getRequest();
        //相应信息封装
        ServerHttpResponse response = exchange.getResponse();
        //如果请求路径是登录放行
        String s = request.getURI().getPath();
        if (s.contains("login")){
            return chain.filter(exchange);
        }
        //判断有没有token
        String token = request.getHeaders().getFirst("token");
        //判断token是否为空，校验token
           if (token == null  ||  !JwtUtils.checkToken(token)){
               //401状态
               response.setStatusCode(HttpStatus.UNAUTHORIZED);

               response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
               return response.writeWith(Flux.just(response.bufferFactory().wrap("请您先登录！".getBytes(Charset.forName("UTF-8")))));

           }

           return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
